package com.task.scheduling;

import com.task.scheduling.service.ApplicationReadyAware;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.scheduling.annotation.EnableScheduling;

import java.util.*;

@SpringBootApplication
@MapperScan("com.task.scheduling.dao")
@EnableScheduling
public class TaskSchedulingApplication {

	public static void main(String[] args) throws Exception{

		SpringApplication application = new SpringApplication(TaskSchedulingApplication.class);

		application.addListeners(new ApplicationListener<ApplicationReadyEvent>() {
			@Override
			public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
				TaskSchedulingApplication.afterApplicationReady(applicationReadyEvent);
			}
		});
		application.run(args);
	}

	/**executionTime
	 * 将能够操作的应用进行排序
	 * @param values
	 */
	private static <T extends ApplicationReadyAware> void sort(List<T> values){
		Collections.sort(values, new Comparator<Ordered>() {
			@Override
			public int compare(Ordered o1, Ordered o2) {
				return o1.getOrder() - o2.getOrder();
			}
		});
	}

	private static void afterApplicationReady(ApplicationReadyEvent event) {
		//在spring加载完成之后，添加通知信息
		ConfigurableApplicationContext applicationContext = event.getApplicationContext();
		Map<String, ApplicationReadyAware> beansOfType = applicationContext.getBeansOfType(ApplicationReadyAware.class);
		if (false == beansOfType.isEmpty()) {
			List<ApplicationReadyAware> values = new ArrayList<>(beansOfType.values());
			sort(values);
			for (ApplicationReadyAware value : values) {
				value.afterApplicationReady(applicationContext);
			}
		}
	}
}
